package com.newgoldcurrency.activities.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.AdError;
import com.anythink.interstitial.api.ATInterstitial;
import com.anythink.interstitial.api.ATInterstitialListener;
import com.anythink.rewardvideo.api.ATRewardVideoAd;
import com.anythink.rewardvideo.api.ATRewardVideoListener;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.activities.CountDownActivity;
import com.newgoldcurrency.activities.NoticeActivity;
import com.newgoldcurrency.activities.SurpriseActivity;
import com.newgoldcurrency.activities.emailverifyandmodify.EmailVerifyAndModifyActivity;
import com.newgoldcurrency.adapter.NoticeAdapter;
import com.newgoldcurrency.bean.BannerBean;
import com.newgoldcurrency.bean.NoticeBean;
import com.newgoldcurrency.bean.ShowBean;
import com.newgoldcurrency.databinding.FragmentHomeBinding;
import com.newgoldcurrency.utils.NettyClient;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;
import com.newgoldcurrency.view.LoadingDialog;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HomeFragment extends Fragment {
    private FragmentHomeBinding binding;
    private NavController controller;
    private final List<Call> calls = new ArrayList<>();
    private final List<BannerBean> bannerData = new ArrayList<>();
    private NoticeAdapter adp;
    private final List<NoticeBean> noticeData = new ArrayList<>();
    private MainActivity activity;
    private int current = 1;
    private long seconds = 0;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (seconds>1){
                seconds--;
                if (binding!=null) binding.loadingView.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.bg_button_gold_10,null));
                if (binding!=null)binding.homeRemingTip.setVisibility(View.GONE);
                if (binding!=null)binding.homeTriangle.setVisibility(View.GONE);
                handler.postDelayed(this, 1000);
            } else {
                if (binding!=null)binding.loadingView.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.bg_button_gold_grey,null));
                if (binding!=null)binding.homeRemingTip.setVisibility(View.VISIBLE);
                if (binding!=null) binding.homeTriangle.setVisibility(View.VISIBLE);
            }
        }
    };
    private NettyClient nettyClient;
    private MediaPlayer mediaPlayer;
    private LoadingDialog loading_dialog;
    private long mClickTime;
    private ActivityResultLauncher<Intent> launcher;
    private ATInterstitial mInterstitialAd;
    private ATRewardVideoAd mRewardVideoAd;

    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
    @SuppressLint("SetTextI18n")
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (MainActivity) getActivity();
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        binding.homeEmailVerify.setOnClickListener(v -> {
            if (checkDoubleClick()) launcher.launch(new Intent(v.getContext(), EmailVerifyAndModifyActivity.class));
        });
        binding.homeInviteShare.setOnClickListener(v -> {
            if (checkDoubleClick())controller.navigate(R.id.nav_invite);
        });
        binding.homeWallet.setOnClickListener(v ->{
            if (checkDoubleClick()) controller.navigate(R.id.nav_wallet);
        } );
        binding.homeMiner.setOnClickListener(v ->{
            if (checkDoubleClick()) controller.navigate(R.id.nav_miner);
        } );
        binding.homeFollow.setOnClickListener(v ->{
            if (checkDoubleClick()){
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://goldrr.com/?follow/")));
            }
        });
        binding.homeChain.setOnClickListener(v -> {
            if (checkDoubleClick()) controller.navigate(R.id.nav_chain);
        });
        binding.homeAccount.setText(getString(R.string.account, App.userBean.mail));
        binding.homeInvitationCode.setText(App.userBean.invitation_code);
        binding.loadingView.setOnClickListener(v -> {
            if (checkDoubleClick()) {
                if (loading_dialog != null && !loading_dialog.isShowing()) {
                    loading_dialog.show();
                    HashMap<String, String> map = new HashMap<>();
                    map.put("token", App.sp.getString("token", ""));
                    Network.post(map, "miner/mine", call -> {
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                activity.runOnUiThread(() -> {
                                    e.printStackTrace();
                                    loading_dialog.dismiss();
                                });
                            }
                            @Override
                            public void onResponse(@NonNull Call call, @NonNull Response response) {
                                activity.runOnUiThread(() -> {
                                    try {
                                        String str = Objects.requireNonNull(response.body()).string();
                                        if (Tools.isJson(str)) {
                                            JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                            if (jo.get("message").getAsString().equals("Mine success")) {
                                                Tools.dialog_mine(activity, "Mine success", "collect:" + jo.get("data").getAsJsonObject().get("collect").getAsString(), "Confirm", true, v1 -> {
                                                    refresh(true, null);
                                                    if (App.ShowBean.hasInterstitial){
                                                        Tools.log("有插屏，加载");
                                                        mInterstitialAd.load();
                                                    }else {
                                                        loading_dialog.dismiss();
                                                    }
                                                });
                                            } else {
                                                loading_dialog.dismiss();
                                                startActivity(new Intent(activity, CountDownActivity.class).putExtra("countDown", jo.get("data").getAsJsonObject().get("countDown").getAsString()));
                                            }
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                        });
                        calls.add(call);
                    });
                }
            }
        });
        adp = new NoticeAdapter(activity, noticeData);
        binding.homeNoticeList.setAdapter(adp);
        binding.homeNoticeList.setOnItemClickListener((parent, view, position, id) -> {
            NoticeBean bean = noticeData.get(position);
            if (checkDoubleClick()) startActivity(new Intent(activity, NoticeActivity.class).putExtra("id",bean.id).putExtra("image",bean.image));
        });
        binding.homeRefresh.setRefreshHeader(new ClassicsHeader(activity));
        binding.homeRefresh.setRefreshFooter(new ClassicsFooter(activity));
        binding.homeRefresh.setOnRefreshListener(refreshLayout -> refresh(true, refreshLayout));
        binding.homeRefresh.setOnLoadMoreListener(refreshLayout -> refresh(false, refreshLayout));
        controller=Navigation.findNavController(container);
        controller = Navigation.findNavController(container);
        binding.homeTotleBalance.setOnClickListener(v ->{
            if (checkDoubleClick()) controller.navigate(R.id.nav_income);
        });
        binding.homeBell.setOnClickListener(v -> {
            boolean openbell = App.sp.getBoolean("openBell", false);
            SharedPreferences.Editor edit = App.sp.edit();
            if (openbell) {
                edit.putBoolean("openBell", false);
                binding.homeBell.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.bell_close,null));
                pauseBell();
            } else {
                edit.putBoolean("openBell", true);
                binding.homeBell.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.bell,null));
            }
            edit.apply();
        });

        initBanner();
        binding.homeBanner.addBannerLifecycleObserver(this);
        initialBell();
        initReward();
        showCoinOrRate();
        checkVerify();
        refresh(true, null);
        nettyClient = new NettyClient(jo -> activity.runOnUiThread(() -> {
            String cmd = jo.get("cmd").getAsString();
            switch (cmd) {
                case "REMAINING":
                    falldelay=jo.get("speed").getAsInt();
                    end=jo.get("msg").getAsLong();
                    if (isFirst){
                        isFirst=false;
                        handler_reming.postDelayed(runnable_reming, 0);
                        playBell();
                    }
                    break;
                case "MESSAGE":
                    int mun = jo.get("msg").getAsInt();
                    if (mun > 99) {
                        binding.homeMsg.setText("99+");
                        binding.homeMsg.setVisibility(View.VISIBLE);
                    } else if (mun > 0) {
                        if (mun < 10) binding.homeMsg.setText(" " + mun + " ");
                        else binding.homeMsg.setText(mun + "");
                        binding.homeMsg.setVisibility(View.VISIBLE);
                    } else binding.homeMsg.setVisibility(View.INVISIBLE);
                    break;
            }
        }));
        initInterstitial();
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode()==3){
                controller.navigate(R.id.nav_income);
            }else {
                refresh(true, null);
                binding.homeAccount.setText(getString(R.string.account, App.userBean.mail));
            }
        });
        return binding.getRoot();
    }
    private void initBanner() {
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Tools.getScreenWidth(activity) / 2);
        p.height=300;
        binding.homeBanner.setLayoutParams(p);
        binding.homeBanner.setAdapter(new BannerImageAdapter<BannerBean>(bannerData) {
            @Override
            public void onBindView(BannerImageHolder holder, BannerBean data, int position, int size) {
                if (holder!=null&&holder.imageView!=null)Glide.with(holder.imageView).load(data.imageUrl).thumbnail(Glide.with(holder.itemView).load(R.drawable.transparent)).into(holder.imageView);
            }
        }).setIntercept(false).setBannerRound(20f)
                .setOnBannerListener((data,position) ->{
                    String url = ((BannerBean) data).navigatorUrl;
                    if (!url.equals("")) startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url)));
                });
    }
    //________________________________________________________________________________________________________________________________________________
    Handler handler_reming = new Handler();
    Runnable runnable_reming = new Runnable() {
        @Override
        public void run() {
            if (now>end){
                if (binding!=null)binding.homeRemainGold.setText(String.valueOf(--now));
                handler_reming.postDelayed(this, falldelay);
            }else {
                isFirst=true;
                pauseBell();
            }
        }
    };
    private int falldelay=50;
    private long end=0;
    private long now=0;
    private boolean isFirst=true;
    //________________________________________________________________________________________________________________________________________________
    private void checkVerify() {
        if (App.sql.getMailVerify(App.userBean.mail, null)) {
            binding.homeVerification.setVisibility(View.INVISIBLE);
            binding.homeVerification.setText("");
            binding.homeVerified.setVisibility(View.VISIBLE);
            binding.homeEmailVerify.setEnabled(false);
        } else {
            binding.homeVerification.setText(getString(R.string.verification));
            binding.homeVerified.setVisibility(View.INVISIBLE);
            binding.homeVerification.setVisibility(View.VISIBLE);
            binding.homeEmailVerify.setEnabled(true);
        }
    }
    private void pauseBell() {
        if (binding!=null)binding.homeBell.clearAnimation();
        if (mediaPlayer != null) mediaPlayer.pause();
    }
    private void playBell() {
        if (App.sp.getBoolean("openBell", false)) {
            binding.homeBell.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.shake_bell));
            if (mediaPlayer == null) {
                mediaPlayer = MediaPlayer.create(activity, R.raw.bell);
                mediaPlayer.setLooping(true);
            }
            mediaPlayer.start();
        }
    }
    private void initialBell() {
        boolean openbell = App.sp.getBoolean("openBell", false);
        if (openbell) binding.homeBell.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.bell,null));
        else binding.homeBell.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.bell_close,null));
    }
    private void showCoinOrRate() {
        if (loading_dialog==null) loading_dialog=new LoadingDialog(activity);
        if (App.hasGift) binding.homeRain.start(2);
        binding.homeRain.addClickListener(() -> {
            if (loading_dialog.isShowing()) loading_dialog.dismiss();
            loading_dialog.show();
            App.hasGift = false;
            mRewardVideoAd.load();
        });
    }
    public void initReward(){
        mRewardVideoAd = new ATRewardVideoAd(activity, "b620dbae8cb06a");
        Map<String, Object> map=new HashMap<>();
        map.put("token",App.sp.getString("token",""));
        map.put(ATAdConst.KEY.USER_CUSTOM_DATA,App.sp.getString("token",""));
        mRewardVideoAd.setLocalExtra(map);
        mRewardVideoAd.setAdListener(new ATRewardVideoListener() {
            @Override
            public void onRewardedVideoAdLoaded() {
                if (loading_dialog.isShowing()) loading_dialog.dismiss();
                mRewardVideoAd.show(activity);
            }
            @Override
            public void onRewardedVideoAdFailed(AdError adError) {
                if (loading_dialog.isShowing()) loading_dialog.dismiss();
            }
            @Override
            public void onRewardedVideoAdPlayStart(ATAdInfo atAdInfo) {
            }
            @Override
            public void onRewardedVideoAdPlayEnd(ATAdInfo atAdInfo) {
            }
            @Override
            public void onRewardedVideoAdPlayFailed(AdError adError, ATAdInfo atAdInfo) {
            }
            @Override
            public void onRewardedVideoAdClosed(ATAdInfo atAdInfo) {
                launcher.launch(new Intent(activity, SurpriseActivity.class));
            }
            @Override
            public void onRewardedVideoAdPlayClicked(ATAdInfo atAdInfo) {
            }
            @Override
            public void onReward(ATAdInfo atAdInfo) {
            }
        });
    }
    private void refresh(boolean isRefresh, RefreshLayout layout) {
        for (Call call : calls) call.cancel();
        if (isRefresh) {
            noticeData.clear();
            current = 1;
        } else current++;
        HashMap<String, String> map = new HashMap<>();
        map.put("token", App.sp.getString("token", ""));
        map.put("pageNumber", String.valueOf(current));
        map.put("pageSize", "5");
        Network.post(map, "homepage/homePageInfo", call -> {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"})
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    activity.runOnUiThread(() -> {
                        try {
                            String str = Objects.requireNonNull(response.body()).string();
                            if (Tools.isJson(str)) {
                                JsonObject jo = JsonParser.parseString(str).getAsJsonObject().get("data").getAsJsonObject();
                                App.ShowBean = new Gson().fromJson(jo, ShowBean.class);
                                Tools.log("广告控制："+App.ShowBean.toString());
                                SharedPreferences.Editor edit = App.sp.edit();
                                edit.putBoolean("hasOpen",App.ShowBean.hasOpen);
                                edit.apply();
                                int mun = jo.get("messageCount").getAsInt();
                                if (mun > 99) {
                                    binding.homeMsg.setText("99+");
                                    binding.homeMsg.setVisibility(View.VISIBLE);
                                } else if (mun > 0) {
                                    if (mun < 10) binding.homeMsg.setText(" " + mun + " ");
                                    else binding.homeMsg.setText(mun + "");
                                    binding.homeMsg.setVisibility(View.VISIBLE);
                                } else {
                                    binding.homeMsg.setVisibility(View.INVISIBLE);
                                }
                                String balance = String.valueOf(jo.get("goldCoins").getAsDouble());
                                App.my_balance = balance;
                                binding.homeTotleBalance.setText(getString(R.string.total_balance, balance));
                                if (isFirst){
                                    now=jo.get("remainingGold").getAsLong();
                                    binding.homeRemainGold.setText(String.valueOf(now));
                                }
                                //开始延迟
                                long m;
                                m = jo.get("countDown").getAsLong();
                                if (m > 0) {
                                    seconds = m / 1000;
                                    binding.loadingView.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.bg_button_gold_10,null));
                                    binding.homeRemingTip.setVisibility(View.GONE);
                                    binding.homeTriangle.setVisibility(View.GONE);
                                } else {
                                    binding.loadingView.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.bg_button_gold_grey,null));
                                    binding.homeRemingTip.setVisibility(View.VISIBLE);
                                    binding.homeTriangle.setVisibility(View.VISIBLE);
                                }
                                bannerData.clear();
                                bannerData.addAll(new Gson().fromJson(jo.get("banners"), new TypeToken<List<BannerBean>>() {}.getType()));
                                binding.homeBanner.getAdapter().notifyDataSetChanged();
                                noticeData.addAll(new Gson().fromJson(jo.get("notices"), new TypeToken<List<NoticeBean>>() {
                                }.getType()));
                                adp.notifyDataSetChanged();
                                if (jo.get("verifiedMail").getAsBoolean()) {
                                    App.sql.getMailVerify(App.userBean.mail, "1");
                                    checkVerify();
                                }
                            }
                            if (layout != null) {
                                if (isRefresh) layout.finishRefresh();
                                else layout.finishLoadMore();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                }
            });
            calls.add(call);
        });
    }

    public void initInterstitial(){
        mInterstitialAd = new ATInterstitial(activity, "b620dbae9d4e76");
        mInterstitialAd.setAdListener(new ATInterstitialListener() {
            @Override
            public void onInterstitialAdLoaded() {
                loading_dialog.dismiss();
                mInterstitialAd.show(activity);
            }
            @Override
            public void onInterstitialAdLoadFail(AdError adError) {
              Tools.log("onInterstitialAdLoadFail: "+adError);
                loading_dialog.dismiss();
            }
            @Override
            public void onInterstitialAdClicked(ATAdInfo atAdInfo) { }
            @Override
            public void onInterstitialAdShow(ATAdInfo atAdInfo) { }
            @Override
            public void onInterstitialAdClose(ATAdInfo atAdInfo) {
            }
            @Override
            public void onInterstitialAdVideoStart(ATAdInfo atAdInfo) { }
            @Override
            public void onInterstitialAdVideoEnd(ATAdInfo atAdInfo) { }
            @Override
            public void onInterstitialAdVideoError(AdError adError) {
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        for (Call call : calls) call.cancel();
        handler.removeCallbacks(runnable);
        handler_reming.removeCallbacks(runnable_reming);
        pauseBell();
        isFirst=true;
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
        }
        if (loading_dialog!=null&&loading_dialog.isShowing())loading_dialog.dismiss();
        binding = null;
    }
    @Override
    public void onPause() {
        super.onPause();
        App.hasGift = false;
    }
    @Override
    public void onStop() {
        super.onStop();
        nettyClient.close();
        if (binding != null)binding.homeBanner.stop();
    }
    @Override
    public void onStart() {
        super.onStart();
        nettyClient.start("HOME");
        if (binding != null)binding.homeBanner.start();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        App.hasGift = false;
        if (binding != null)binding.homeBanner.destroy();
        binding=null;
    }
}